﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.IO;
using System.Threading;

[RequireComponent(typeof(AudioSource))]
public class ReaderNeuralNet : MonoBehaviour
{
	private ArrayList files;
    HashSet<string> oldurls;
    NeuralNet nn = new NeuralNet();
    WWW www;
    public Texture2D img, imgProg;
    private string text, outext;
    private int pos;
    private string cururl;
    private int wpos;
    private int lastch;
    private float imgOffsetX;
    private float imgOffsetY;

	public void Awake(){
		nn.Init ();
        outext = "";
        files = new ArrayList();
        oldurls = new HashSet<string>();
        files.Add("http://www.baidu.com/s?wd=%E9%81%93%E6%95%99");
        files.Add("http://www.hao123.com/");
        files.Add("http://www.baidu.com/s?wd=%E9%81%93%E6%95%99");
        
        //if(Directory.Exists(Server.MapPath("a")))
        //{
        //    //所有子文件夹
        //    foreach(string item in Directory.GetDirectories(Server.MapPath("a")))
        //    {
        //        Response.Write("<b>文件夹：" + item + "</b><br/>");
        //        DirectoryInfo directoryinfo = new DirectoryInfo(item);
        //        Response.Write("名称：" + directoryinfo.Name + "<br/>");
        //        Response.Write("路径：" + directoryinfo.FullName + "<br/>");
        //        Response.Write("创建时间：" + directoryinfo.CreationTime + "<br/>");
        //        Response.Write("上次访问时间：" + directoryinfo.LastAccessTime + "<br/>");
        //        Response.Write("上次修改时间：" + directoryinfo.LastWriteTime + "<br/>");
        //        Response.Write("父文件夹：" + directoryinfo.Parent + "<br/>");
        //        Response.Write("所在根目录：" + directoryinfo.Root + "<br/>");
        //        Response.Write("<br/>");
        //    }

        //    //所有子文件
        //    foreach (string item in Directory.GetFiles(Server.MapPath("a")))
        //    {
        //        Response.Write("<b>文件：" + item + "</b><br/>");
        //        FileInfo fileinfo = new FileInfo(item);
        //        Response.Write("名称：" + fileinfo.Name + "<br/>");
        //        Response.Write("扩展名：" + fileinfo.Extension +"<br/>");
        //        Response.Write("路径：" + fileinfo.FullName +"<br/>");
        //        Response.Write("大小：" + fileinfo.Length +"<br/>");
        //        Response.Write("创建时间：" + fileinfo.CreationTime +"<br/>");
        //        Response.Write("上次访问时间：" + fileinfo.LastAccessTime +"<br/>");
        //        Response.Write("上次修改时间：" + fileinfo.LastWriteTime +"<br/>");
        //        Response.Write("所在文件夹：" + fileinfo.DirectoryName +"<br/>");
        //        Response.Write("文件属性：" + fileinfo.Attributes +"<br/>");
        //        Response.Write("<br/>");
        //    }
        //}
	}

	// Use this for initialization
	public  void Start() {
		nn.Start ();

	}

    IEnumerator HandleWWWRequest(string url, System.Action<WWW> onSuccess)
    {
        WWW www = new WWW(url.Replace("https","http"));
        Debug.LogWarning("Request URL: "+url);
        yield return www;
        if (string.IsNullOrEmpty(www.error))
        {
            onSuccess(www);
        }
        else
        {
            cururl = null;
            Debug.LogWarning("WWW request returned an error: "+ www.error);
        }
    }

    // Update is called once per frame
    public void Update()
    {
        if (www == null)
        {
            if (cururl == null && files.Count > 0)
            {
                cururl = (string)files[0];
                oldurls.Add(cururl);
                files.RemoveAt(0);
                StartCoroutine(HandleWWWRequest(cururl, (w) =>
                {
                    www = w;
                    Debug.Log("Load Url: " + cururl);
                }));
            }
        }
        else if (www.progress >= 1f)
        {
            if (text == null)
            {
                text = www.text;
                parseUrls(text);
            }
            else
            {
                if (pos < text.Length)
                {
                    char ch = text[pos++];
                    //text = text.Remove(0, 1);
                    if (ch > 0)
                    {
                        nn.inputValue(1,0, (short)lastch);
                        nn.inputValue(2, 0, (short)ch);
                        nn.inputValue(3, 0, (short)(pos < text.Length ? text[pos] : 0));
                    }
                    lastch = ch;
                    nn.inputValue(4, 0, (short)imgOffsetX);
                    nn.inputValue(5, 0, (short)imgOffsetY);

                    nn.ThreadUpdate();

                    int outchar = 0;
                    for (int i = 0; i < 16; i++)
                    {
                        outchar += nn.checkOut(i,0) ? (1 << i) : 0;
                    }
                    if (outchar > 0)
                    {
                        //Debug.Log("Output: "+ch);
                        outext = outext.Insert(outext.Length, "" + (char)outchar);
                        if (outext.Length > 1024)
                        {
                            outext = outext.Remove(0);
                        }
                    }
                    nn.inputValue(0,0, (short)ch);
                    if (nn.checkOut(16,0))
                    {
                        imgOffsetX++;
                    }
                    if (nn.checkOut(17,0))
                    {
                        imgOffsetX--;
                    }
                    if (nn.checkOut(18,0))
                    {
                        imgOffsetY++;
                    }
                    if (nn.checkOut(19,0))
                    {
                        imgOffsetY--;
                    }
                    if (imgOffsetX > Screen.width / 2)
                    {
                        imgOffsetX = -Screen.width / 2;
                    }
                    if (imgOffsetX < -Screen.width / 2)
                    {
                        imgOffsetX = Screen.width / 2;
                    }
                    if (imgOffsetY > Screen.height / 2)
                    {
                        imgOffsetY = -Screen.height / 2;
                    }
                    if (imgOffsetY < -Screen.height / 2)
                    {
                        imgOffsetY = Screen.height / 2;
                    }
                }
                else
                {
                    www = null;
                    cururl = null;
                    text = null;
                    pos = 0;
                    wpos = 0;
                    lastch = 0;
                }
            }
        }
        else
        {

        }
    }

    private void parseUrls(string text)
    {
        int i = 0;
        while ((i=text.IndexOf("href=\"", i + 1))!=-1)
        {
            int end = text.IndexOf("\"",i+6);
            if(end==-1){
                continue;
            }
            string u = text.Substring(i+6,end-i-6);
            if(u.StartsWith("/")){
                u = cururl.Substring(0, cururl.LastIndexOf("/"))+u;
            }
            if (files.Contains(u) == false && oldurls.Contains(u) == false)
            {
                files.Add(u);
                Debug.Log(u);
            }
        }
    }

	void OnGUI(){
        float imgWidth = 50f;
        GUI.Label(new Rect(5f,5f,200f,20f),"Pos: "+pos);
        GUI.DrawTexture(new Rect((Screen.width - imgProg.width) / 2f, 10f, imgProg.width * (www!=null?www.progress:0f), imgProg.height * 1f), imgProg);
        if (text != null)
        {
            float y = 20f + imgProg.height;
            GUI.TextArea(new Rect(5f, y, Screen.width - 10f, Screen.height/2 - y - 5f), text.Substring(pos, Math.Min(1024, text.Length-pos)));
            GUI.TextArea(new Rect(5f, y + (Screen.height / 2 - y+10f), Screen.width - 10f, Screen.height / 2-y-5f), outext.Substring(0, Math.Min(1024, outext.Length)));
        }

        GUI.DrawTexture(new Rect((Screen.width - imgWidth) / 2f + imgOffsetX, (Screen.height - imgWidth) / 2f + imgOffsetY, imgWidth, imgWidth), img);
	}

	/**
   * path：文件创建目录
   * name：文件的名称
   *  info：写入的内容
   */
	void CreateFile(string path,string name,string info)
	{
		//文件流信息
		StreamWriter sw;
		FileInfo t = new FileInfo(path+"//"+ name);
		if(!t.Exists)
		{
			//如果此文件不存在则创建
			sw = t.CreateText();
		}
		else
		{
			//如果此文件存在则打开
			sw = t.AppendText();
		}
		//以行的形式写入信息
		sw.WriteLine(info);
		//关闭流
		sw.Close();
		//销毁流
		sw.Dispose();
	}  

	/**
   * path：读取文件的路径
   * name：读取文件的名称
   */
	ArrayList LoadFile(string path,string name)
	{
		//使用流的形式读取
		StreamReader sr =null;
		try{
			sr = File.OpenText(path+"//"+ name);
		}catch(Exception e)
		{
			//路径与名称未找到文件则直接返回空
			return null;
		}
		string line;
		ArrayList arrlist = new ArrayList();
		while ((line = sr.ReadLine()) != null)
		{
			//一行一行的读取
			//将每一行的内容存入数组链表容器中
			arrlist.Add(line);
		}
		//关闭流
		sr.Close();
		//销毁流
		sr.Dispose();
		//将数组链表容器返回
		return arrlist;
	}   

	/**
   * path：删除文件的路径
   * name：删除文件的名称
   */

	void DeleteFile(string path,string name)
	{
		File.Delete(path+"//"+ name);

	}
}